// index.js
// 获取应用实例
import * as echarts from '../../../components/ec-canvas/echarts';
import * as liquidFill from '../../../components/ec-canvas/echarts-liquidfill.min';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp()
const api = app.globalData.api
var chart = null;//仅包含柱状图，折线图，饼图，漏斗图
function initChart(canvas, width, height, dpr) {
    chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  var option = {
    backgroundColor: "#ffffff",
    tooltip: {
      trigger: 'item',
      formatter: "{a}\n{b} : {c}%"
    },
    legend: {
      data: []
    },
    calculable: true,
    series: [
      {
        name: '漏斗图',
        type: 'funnel',
        data: []
      }
    ]
  };
  chart.setOption(option);
  return chart;
}


Page({
  data: {
    menu:[],
    power:[],
    backlog:[],
    message:[],
    active:0,
    tabIndex:0,
    loginState:0,
    show: false,
    companyName:'默认账套',
    selectOption:[],//账套选项
    popup_show:false,
    ec: {
      onInit: initChart
    },
    ec2: {
      lazyLoad: true
    },
    xData:[],
    yData:[],
    setting:[]
  },
    /**选项 */
    chooseSelect(e){
      let that = this;
      api.curlPost('?cla=clientOtherApp&fun=coidOption',{}).then((res)=>{
        that.setData({
          selectOption:res.data.result,
          popup_show:true
        })
      })
    },
      /**选项取消 */
  onCancel(e){
    this.setData({
      popup_show:false
    })
  },
  /**选项切换 */
  onConfirm(event){
    let that = this;
    const { picker, value, index } = event.detail;
    api.curlPost('?cla=clientOtherApp&fun=updateCoid',{id:value.id}).then((res)=>{
      this.setData({
        popup_show:false
      })
      that.requstData();
    })
   
  },
  menu(){
    wx.switchTab({
      url: '../menu/menu',
    })
  },
  setting(){
    wx.navigateTo({
      url: '../setting/setting',
    })
  },
  // 事件处理函数
  onChange(event) {
    this.setData({
      tabIndex:event.detail.name
    })
    let that = this;
    if (event.detail.name == 1) {
      api.curlPost('?cla=clientOtherApp&fun=backlog',{act:'message'}).then((res)=>{
        that.setData({
          message:res.data.result,
        });
     
      })
    }else{
      api.curlPost('?cla=clientOtherApp&fun=backlog',{act:'backlog'}).then((res)=>{
        that.setData({
          backlog:res.data.result,
        });
      })
    }
  },
  navigateTo(e){
    wx.navigateTo({
      url: '../backlog/backlog?tabIndex='+this.data.tabIndex,
    })
  },
  onReady(){
   
  },
  onDialogClose() {
    this.setData({ show: false });
  },
  lookService(){
    wx.navigateTo({
      url: '../about/about?type=用户服务及隐私协议',
    })
  },
  onDialogConfirm(){
    this.setData({ show: false });
    wx.setStorageSync('service', 1)
  },
  onLoad() {
    let that = this;
   
    //登录成功后执行
    app.wxLoginCallback = (code) => {   
      if(code ==1){
        this.ecComponent = this.selectComponent('#mychart-liquidFill');
        setTimeout(function () {
          that.requstData();
          that.initCharts([0])
        }, 1000)

        //用户协议
        // let isAgree = wx.getStorageSync('service');
        // if(!isAgree){
        //   that.setData({
        //     show:true
        //   })
        // }
      }
  }
  },
  onShow(){
    if (this.data.loginState) {
      this.findMenu();
    }
   
  },

  findMenu(){
    let that = this;
    let setting = wx.getStorageSync('setting');
    
    if(api.isBlank(setting)){
      wx.setStorageSync('setting', this.data.setting)
    }else{
      let arr = setting.filter(item=> !item.checked)
      let menu = [];
      let flag = false;
      that.data.power.forEach((item)=>{
        flag = false;
        arr.forEach((v)=>{
          if(item.name == v.name){
            flag = true;
          }
        })
        if(!flag){
          menu.push(item)
        }
     })
    
      this.setData({
        menu
      })
    }
  },
  /**水球图 */
  initCharts: function (value) {
    let that = this;
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart2 = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      console.log(echarts.version);
      // let data = [value, value, value, ];
      chart2.setOption(that.getLiquidOption(value));
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart2 = chart2;
     
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart2;
    });
   
  },
    
  toUrl(e){
    let url = e.currentTarget.dataset.url;
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    let typeId = e.currentTarget.dataset.khid;
    if(api.isBlank(url)){
      wx.showModal({
        title: '提示',
        content: '当前小程序暂不支持处理此类型消息，请前往PC端操作',
        showCancel:false
      })
      return false;
    }
    if(this.data.tabIndex == 1){
      api.curlPost('?cla=messageApp&fun=readed',{id:id}).then((res)=>{

      })
    }
    if(type =='客户跟进'){
      url = '/pages/clientInfo/clientInfo?id='+typeId;
    }
    wx.navigateTo({
      url: url
    })
  },
  requstData(){    
    let that = this;
    api.curlPost('?cla=clientOtherApp&fun=backlog',{act:'backlog'}).then((res)=>{
      that.setData({
        backlog:res.data.result,
        companyName:res.data.companyName,
        loginState:1
      });
     
    })
    //常用功能
    api.curlPost('?cla=clientOtherApp&fun=func').then((res)=>{
      wx.stopPullDownRefresh()
      let setting = [];
       res.data[0].array.forEach((v)=>{
        setting.push({name:v.name,checked:true})
       })
      that.setData({
        menu:res.data[0].array,
        power:res.data[0].array,
        setting:setting,
      });
      that.findMenu();
    })
    //数据看板
    api.curlPost('?cla=clientOtherApp&fun=dataBoard').then((res)=>{
      that.setData({
        dataBoard:res.data,
      });
    })
    //业绩目标
    api.curlPost('?cla=clientOtherApp&fun=salesTarget').then((res)=>{
      that.setData({
        aim:res.data
      });
      let percent = res.data.target>0?(res.data.real/res.data.target).toFixed(2):0;
     
      that.chart2.setOption(that.getLiquidOption([percent]));
    })
    //销售漏斗
    api.curlPost('?cla=clientOtherAppClass&fun=cluesData').then((res)=>{
      let xData = [];
      let yData = [];
      res.data.forEach((v)=>{
        xData.push(v.name)
        yData.push({name:v.name,value:v.data});
      })

      chart.setOption(that.getFunnelOption(xData,yData))
    })
  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if(this.data.loginState){
      this.requstData();
    }
  },

  /**漏斗图 */
 getFunnelOption(xData, yData) {
    var option = {
      backgroundColor: "#ffffff",
      tooltip: {
        trigger: 'item',
        formatter: "{a}\n{b} : {c}%"
      },
      legend: {
        data: xData
      },
      calculable: true,
      series: [
        {
          name: '漏斗图',
          type: 'funnel',
          data: yData
        }
      ]
    };
    return option;
  },
  getLiquidOption(value){
     let option={
      series: [{
          type: 'liquidFill',
          outline: {
            show: false
        },
        label: {
          fontSize: 20
        },
        radius: '90%',
          data: value,
          
        }]
      };
      return option
  },
  /// 长按清理信息
  clearStorage: function (act) {
    app.clearStorage()
  },
})

